package com.example.controller;


import com.example.service.QianfanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

@CrossOrigin(origins = "http://localhost:5173")
@RestController
@RequestMapping("/api")
public class QianfanController {

    @Autowired
    private QianfanService qianfanService;

    @PostMapping("/generate")
    public ResponseEntity<Map<String, Object>> generateMessage(@RequestBody Map<String, Object> payload) {
        String userPrompt = (String) payload.get("userPrompt");
        Integer maxTokens = (Integer) payload.get("maxTokens");
        String role = (String) payload.get("role");

        System.out.println("Received userPrompt: " + userPrompt);
        System.out.println("Received maxTokens: " + maxTokens);
        System.out.println("Received role: " + role);

        Map<String, Object> response = new HashMap<>();
        try {
            String generatedText = qianfanService.callWithMessage(userPrompt, maxTokens, role);
            response.put("output", Collections.singletonMap("text", generatedText));
            return ResponseEntity.ok().body(response);
        } catch (Exception e) {
            response.put("error", "Error: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }
}
